package com.lmt.ymcc.comsumer;

import com.alibaba.fastjson.JSON;
import com.lmt.ymcc.constant.MessageConstant;
import com.lmt.ymcc.domain.MessageSms;
import com.lmt.ymcc.dto.SMSSend2MQ;
import com.lmt.ymcc.exception.GlobalException;
import com.lmt.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-smsmessage-consumer",
        topic = MessageConstant.COURSE_MESSAGE_TOPIC,
        selectorExpression = MessageConstant.COURSE_MESSAGE_TAG_SMS
)
@Slf4j
public class SMSMessageMQConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        try {
            String bodyStr = new String(message.getBody(),"utf-8");
            SMSSend2MQ smsSend2MQ = JSON.parseObject(bodyStr, SMSSend2MQ.class);
            //1.保持发送记录到数据库
            MessageSms messageSms = new MessageSms();
            BeanUtils.copyProperties(smsSend2MQ, messageSms);
            messageSmsService.insert(messageSms);
            //2.调用短信网关发送
            log.info("短信发送成功了");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("短信发送失败");
        }
    }
}